import React, { Component } from 'react'
import { Form, message, Spin, Select, Button } from "antd";
import BillingService from 'containers/financial-management/wait-for-billing/wait-for-billing.service'
import { messages } from "share/common";
const { Option } = Select, { Item } = Form;

class DefaultTicket extends Component {

  formItemLayout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 14 },
  };

  state = {
    vendor: '',
    loading: false,
    formData: [],
    optionLoading: false,
    optionList: [],
    focusIndex: -1,
    saveLoading: false
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps.showSlideFrame === this.props.showSlideFrame)
      return;
    if (!nextProps.showSlideFrame) {
      this.props.form.resetFields();
      return !1;
    }
    this.props.form.resetFields();
    this.setState({ vendor: nextProps.vendor },() => {
      this.initForm()
    })
  }

  initForm = () => {
    const { vendor } = this.state;
    this.setState({ loading: true });
    BillingService.getDefaultTicket(vendor).then(res => {
      this.setState({ loading: false, formData: res.data });
    }).catch(e => {
      this.setState({ loading: false });
      message.error(e.response.data.message);
    })
  };

  handleChangeOption = (item, index) => {
    const { vendor } = this.state;
    this.setState({optionLoading: true});
    BillingService.getVendorInvoiceType(vendor).then(res => {
      this.setState({
        optionLoading: false,
        optionList: res.data,
        focusIndex: index
      });
    }).catch(e => {
      this.setState({optionLoading: false});
      message.error(e.response.data.message);
    });
  };

  handleChange = (value, index) => {
    let { formData, optionList } = this.state;
    let temp = optionList.find(it => it.type === value);
    formData[index] = Object.assign(formData[index], {
      invoiceTypeCode: temp ? temp.type : null,
      invoiceTypeName: temp ? temp.name : null
    });
    this.setState({ formData });
  };

  handleSave = () => {
    const { formData, vendor } = this.state, { close } = this.props;
    this.setState({ saveLoading: true });
    BillingService.saveDefaultTicket(vendor, formData).then(() => {
      this.setState({ saveLoading: false });
      close();
    }).catch(e => {
      this.setState({ saveLoading: false });
      message.error(e.response.data.message);
    });
  };

  render() {
    const { loading, formData, optionLoading, optionList, focusIndex, saveLoading } = this.state,
      { formItemLayout } = this, { getFieldDecorator } = this.props.form;
    return (
      <div>
        <Spin spinning={loading}>
          <Form>
            {
              formData.map((item, index) => {
                return (
                  <Item label={item.legalEntityName} {...formItemLayout}>
                    {getFieldDecorator(item.legalEntityId + '', {
                      initialValue: item.invoiceTypeCode || undefined
                    })(
                      <Select
                        notFoundContent={optionLoading ? <Spin size="small"/> : messages('common.unmatched')/*无匹配结果*/}
                        placeholder={messages('common.please.select')/*请选择*/}
                        onChange={value => this.handleChange(value, index)}
                        allowClear
                        onBlur={() => {this.setState({optionList: [], focusIndex: -1})}}
                        onFocus={() => this.handleChangeOption(item, index)}
                      >
                        {
                          focusIndex !== index ? <Option key={item.invoiceTypeCode}>
                            {item.invoiceTypeName}
                          </Option> : optionList.map(it => <Option key={it.type}>{it.name}</Option>)
                        }
                      </Select>
                    )}
                  </Item>
                )
              })
            }
          </Form>
        </Spin>
        <div className="footer-operate" style={{ backgroundColor: '#ffffff', left: '0px' }}>
          <Button type="primary" onClick={this.handleSave} style={{ margin: '0px 10px' }}
                  loading={saveLoading}>{messages('common.save')/*保存*/}</Button>
          <Button onClick={this.props.close}>{messages('common.cancel')/*取消*/}</Button>
        </div>
      </div>
    )
  }

}

const wrappedDefaultTicket = Form.create()(DefaultTicket);
export default wrappedDefaultTicket;
